package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.TravelComment;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.query.TravelCondition;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.DBHelper;
import jdk.jfr.events.ThrowablesEvent;
import org.omg.CORBA.TRANSACTION_MODE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
//@Transactional
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelRepository repository;
    @Autowired
    private MongoTemplate template;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IDestinationService destinationService;
    @Autowired
    private ITravelService travelService;

    @Override
    public Travel get(String id) {
        Optional<Travel> optional = repository.findById(id);
        if (optional.isPresent()){ //如果游记不为空
            Travel travel = optional.get();
            UserInfo userInfo = userInfoService.get(travel.getUserId());
            Destination dest = destinationService.get(travel.getDestId());
            travel.setAuthor(userInfo);
            travel.setDest(dest);
            return travel;
        }
        return null;
    }

    @Override
    public List<Travel> list() {
        return repository.findAll();
    }

    @Override
    public Page<Travel> query(TravelQuery qo) {
        Query query = new Query();
        if (qo.getState() == Travel.STATE_WAITING || qo.getState() == Travel.STATE_REJECT){
            query.addCriteria(Criteria.where("state").is(qo.getState()));
        }

        if (StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }

        //TravelCondition day = qo.getDay();
        TravelCondition day = TravelCondition.DAY_MAP.get(qo.getDayType());
        if (day != null){
            query.addCriteria(Criteria.where("day").gte(day.getMin()).lte(day.getMax()));
        }
        TravelCondition expend = TravelCondition.PEREXPEND_MAP.get(qo.getPerExpendType());
        if (expend != null){
            query.addCriteria(Criteria.where("perExpend").gte(expend.getMin()).lte(expend.getMax()));
        }

        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(),
                Sort.Direction.ASC,"_id");

        if (qo.getOrderType() == TravelQuery.ORDER_NEW){
            pageable = PageRequest.of(qo.getCurrentPage() -1,qo.getPageSize(),
                    Sort.Direction.DESC,"creatTime");
        }else if (qo.getOrderType() == TravelQuery.ORDER_HOT){
            pageable = PageRequest.of(qo.getCurrentPage() -1,qo.getPageSize(),
                    Sort.Direction.DESC,"viewnum");
        }

        //System.err.println(query);
        Page<Travel> page = DBHelper.query(query,template,Travel.class,pageable,qo);

        for (Travel travel : page){
            travel.setAuthor(userInfoService.get(travel.getUserId()));
        }
        return page;
    }

    @Override
    public void changeState(String id, int state) {

        Travel travel = this.get(id);
        //修改状态需要满足的条件
        if (travel == null){
            throw new LogicException("参数异常");
        }
        if (state == Travel.STATE_RELEASE) {
            travel.setState(Travel.STATE_RELEASE); //设置发布状态
            travel.setReleaseTime(new Date());  //发布时间
        }else if (state == Travel.STATE_REJECT){
            travel.setState(Travel.STATE_REJECT);
            travel.setReleaseTime(null);
        }else if (state == Travel.STATE_OVER){
            travel.setState(Travel.STATE_OVER);
        }
        travel.setLastUpdateTime(new Date());   //最后更新时间
        this.update(travel);
    }

    @Override
    public List<Travel> queryTravelsViewnumTop3(String destId) {

        Pageable pageable = PageRequest.of(0,3, Sort.Direction.DESC,"viewnum");

        List<Travel> list = repository.findByDestId(destId,pageable);
        return list;
    }

    @Override
    public void save(Travel travel) {
        //如果id为"" , spring-data-mongodb不会将自动生成的id自动注入
        travel.setId(null);
        repository.save(travel);
    }

    @Override
    public void update(Travel travel) {
        repository.save(travel);
    }

    @Override
    public void saveOrUpdate(Travel travel) {
        //添加和更新 都需要的参数
        Destination dest = destinationService.get(travel.getDestId());
        travel.setDestName(dest.getName()); //设置目的地名称
        //最后更新时间
        travel.setLastUpdateTime(new Date());
        if (StringUtils.hasLength(travel.getId())){
            //查询
            Travel travel2 = travelService.get(travel.getId());
            //替换
            travel2.setReleaseTime(travel2.getReleaseTime());
            travel2.setCreateTime(travel2.getCreateTime());
            //更新
            this.update(travel);
        }else {
            travel.setId(null);
            travel.setCreateTime(new Date());
            this.save(travel);
        }
    }

}
